package cn.com.thinvent.dispatch.service.biz.impl;

import cn.com.thinvent.dispatch.dao.ModelDatasourceMapper;
import cn.com.thinvent.dispatch.entity.ModelDatasource;
import cn.com.thinvent.dispatch.entity.file.fileShowVo;
import cn.com.thinvent.dispatch.entity.response.DataSourceDetailResponse;
import cn.com.thinvent.dispatch.entity.response.PagedGridResult;
import cn.com.thinvent.dispatch.entity.response.TableFieldsResponse;
import cn.com.thinvent.dispatch.entity.response.TablesResponse;
import cn.com.thinvent.dispatch.service.biz.DataSourceService;
import cn.com.thinvent.dispatch.service.biz.util.DataBaseUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.*;
import java.util.List;
import java.util.Map;

@Component
public class DataSourceServiceImpl implements DataSourceService {

    @Resource
    private ModelDatasourceMapper modelDatasourceMapper;

    @Override
    public PagedGridResult<ModelDatasource> list(Integer pageNum, Integer pageSize) {
        PagedGridResult<ModelDatasource> pagedGridResult = new PagedGridResult<>();
        Integer pageBegin = (pageNum - 1) * pageSize;   // 从第几条数据开始获取
        List<ModelDatasource> list = modelDatasourceMapper.list(pageBegin, pageSize);
        Long count = modelDatasourceMapper.count(pageBegin, pageSize);
        pagedGridResult.setRows(list);
        pagedGridResult.setRecords(count);
        pagedGridResult.setTotal((Integer.parseInt(count.toString()) + pageSize - 1 )/ pageSize);
        pagedGridResult.setPage(pageNum);
        return pagedGridResult;
    }

    @Override
    public ModelDatasource saveOrUpdate(ModelDatasource modelDatasource) {
        if(modelDatasource.getId() == null) {
            modelDatasourceMapper.insert(modelDatasource);
        } else {
            modelDatasourceMapper.update(modelDatasource);
        }
        return modelDatasource;
    }

    @Override
    public TablesResponse getTables(ModelDatasource modelDatasource) {
        TablesResponse tablesResponse = new TablesResponse();

        Connection connection = null;
        try {
            connection = DataBaseUtil.getConnection(modelDatasource);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            List<String> tables = DataBaseUtil.getTables(connection, modelDatasource.getDatastore());
            tablesResponse.setTables(tables);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return tablesResponse;
    }

    @Override
    public TableFieldsResponse getTableFields(ModelDatasource modelDatasource) {
        TableFieldsResponse tableFieldsResponse = new TableFieldsResponse();

        try {
            List<String> tableField = DataBaseUtil.getTableField(DataBaseUtil.getConnection(modelDatasource), modelDatasource.getDatastore(), modelDatasource.getDataTable());
            tableFieldsResponse.setFields(tableField);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return tableFieldsResponse;
    }

    @Override
    public void delUnStruct(Integer dId, String filePath) {
        modelDatasourceMapper.delUnStruct(dId);

        //同时删除对应文本
        String os = System.getProperty("os.name").toLowerCase();
        if(os.charAt(0) != 'w') {
            File file = new File(filePath);
            boolean delete = file.delete();
            if (!delete) {
                System.out.println("文件：" + filePath + " 清除失败！");
            }
            /*清除备份文件*/
            // 获取文件名
            String fileName = file.getName();
            // 定义文件夹路径和文件名
            String folderPath = "/fagai/pdffiles/";
            // 使用 Paths.get 方法合并路径
            File folder = new File(folderPath);
            File file2 = new File(folder, fileName);
            boolean delete2 = file2.delete();
            if (!delete2) {
                System.out.println("文件：" + folderPath + "/"+ fileName + " 清除失败！");
            }
        }

    }

    @Override
    public DataSourceDetailResponse detail(Integer datasourceId, Integer pageNum, Integer pageSize) throws SQLException, ClassNotFoundException, IOException {
        DataSourceDetailResponse dataSourceDetailResponse = new DataSourceDetailResponse();
        ModelDatasource modelDatasource = modelDatasourceMapper.queryById(datasourceId);
        // 获取数据源表字段信息
        List<Map<String, Object>> fieldValues = DataBaseUtil.getFieldValues(modelDatasource, pageNum, pageSize);
        dataSourceDetailResponse.setMapList(fieldValues);
        return dataSourceDetailResponse;
    }

    @Override
    public PagedGridResult<fileShowVo> listUnStruct(Integer pageNum, Integer pageSize, Integer tagId) {
        PagedGridResult<fileShowVo> pagedGridResult = new PagedGridResult<>();
        Integer pageBegin = (pageNum - 1) * pageSize;
        List<fileShowVo> list = modelDatasourceMapper.listUnStruct(pageBegin, pageSize,tagId);

        Long count = modelDatasourceMapper.count1(pageBegin, pageSize,tagId);
        pagedGridResult.setRows(list);
        pagedGridResult.setRecords(count);
        pagedGridResult.setTotal((Integer.parseInt(count.toString()) + pageSize - 1 )/ pageSize);
        pagedGridResult.setPage(pageNum);
        return pagedGridResult;
    }
}
